import logging
import os
from concurrent.futures import ThreadPoolExecutor
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

# 获取当前脚本所在的目录，即项目根目录
project_root = os.path.dirname(os.path.abspath(__file__))
log_dir = os.path.join(project_root, 'logs')
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

info_log_path = os.path.join(log_dir, 'info.log')
info_handler = logging.FileHandler(info_log_path)
info_handler.setLevel(logging.INFO)
# 构建完整的错误日志文件路径
error_log_path = os.path.join(log_dir, 'error.log')
error_handler = logging.FileHandler(error_log_path)
error_handler.setLevel(logging.ERROR)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
info_handler.setFormatter(formatter)
error_handler.setFormatter(formatter)
logger.addHandler(info_handler)
logger.addHandler(error_handler)

executor = ThreadPoolExecutor(max_workers=1)

app = FastAPI(title="AI Assistant API")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

from app.api.v1.endpoints import auth, chat

app.include_router(auth.router, prefix="/api/v1/auth", tags=["auth"])
app.include_router(chat.router, prefix="/api/v1/chat", tags=["chat"])


@app.on_event("startup")
async def startup_event():
    global executor
    executor = ThreadPoolExecutor(max_workers=1)
    logger.info("应用启动，线程池已创建")


@app.on_event("shutdown")
async def shutdown_event():
    global executor
    executor.shutdown()
    logger.info("应用关闭，线程池已清理")


@app.get("/")
def read_root():
    logger.info("访问根路径")
    return {"message": "Welcome to the AI Assistant API"}